"use client"

import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Download, FileX } from "lucide-react"
import { useState, useEffect, useCallback } from "react"

interface FileItem {
  id: number
  fileName: string
  fileSize?: number
  mimeType?: string
  isDirectory: boolean
}

interface FilePreviewDialogProps {
  file: FileItem | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onDownload: (id: number, fileName: string) => void
  // 分享文件相关参数
  shareId?: string
  sharePassword?: string
}

// 根据文件扩展名猜测 MIME 类型
function guessMimeTypeFromFileName(fileName: string): string {
  const ext = fileName.split('.').pop()?.toLowerCase()
  if (!ext) return ""
  
  const mimeTypes: Record<string, string> = {
    // 图片
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    png: "image/png",
    gif: "image/gif",
    webp: "image/webp",
    svg: "image/svg+xml",
    bmp: "image/bmp",
    ico: "image/x-icon",
    
    // 视频
    mp4: "video/mp4",
    webm: "video/webm",
    ogg: "video/ogg",
    mov: "video/quicktime",
    avi: "video/x-msvideo",
    mkv: "video/x-matroska",
    
    // 音频
    mp3: "audio/mpeg",
    wav: "audio/wav",
    oga: "audio/ogg",
    m4a: "audio/mp4",
    flac: "audio/flac",
    aac: "audio/aac",
    
    // 文档
    pdf: "application/pdf",
    doc: "application/msword",
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    xls: "application/vnd.ms-excel",
    xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ppt: "application/vnd.ms-powerpoint",
    pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    
    // 文本
    txt: "text/plain",
    html: "text/html",
    htm: "text/html",
    css: "text/css",
    js: "text/javascript",
    jsx: "text/javascript",
    ts: "text/typescript",
    tsx: "text/typescript",
    json: "application/json",
    xml: "text/xml",
    csv: "text/csv",
    md: "text/markdown",
    markdown: "text/markdown",
    yaml: "text/yaml",
    yml: "text/yaml",
    log: "text/plain",
    ini: "text/plain",
    cfg: "text/plain",
    conf: "text/plain",
    sh: "text/plain",
    bat: "text/plain",
    py: "text/x-python",
    java: "text/x-java",
    c: "text/x-c",
    cpp: "text/x-c",
    h: "text/x-c",
    php: "text/x-php",
    rb: "text/x-ruby",
    go: "text/x-go",
    rs: "text/x-rust",
    sql: "text/x-sql",
    
    // 压缩文件
    zip: "application/zip",
    rar: "application/x-rar-compressed",
    "7z": "application/x-7z-compressed",
    tar: "application/x-tar",
    gz: "application/gzip",
  }
  
  return mimeTypes[ext] || ""
}

export function FilePreviewDialog({ file, open, onOpenChange, onDownload, shareId, sharePassword }: FilePreviewDialogProps) {
  const [imageError, setImageError] = useState(false)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [textContent, setTextContent] = useState<string>("")
  const [textError, setTextError] = useState(false)

  // 统一的文件下载函数
  const fetchFileContent = useCallback(async (fileId: number): Promise<Response> => {
    // 如果是分享文件，使用分享下载接口
    if (shareId) {
      const downloadUrl = sharePassword 
        ? `/api/shares/${shareId}/download?password=${sharePassword}`
        : `/api/shares/${shareId}/download`
      return await fetch(downloadUrl)
    } else {
      // 普通文件使用下载接口
      const token = localStorage.getItem("driveJWTToken")
      return await fetch(`/api/files/download/${fileId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
    }
  }, [shareId, sharePassword])

  // 使用 useEffect 获取带认证的预览内容
  useEffect(() => {
    if (!file || !open) {
      // 清理之前的 Blob URL
      if (previewUrl) {
        URL.revokeObjectURL(previewUrl)
        setPreviewUrl(null)
      }
      setTextContent("")
      setTextError(false)
      return
    }

    const mime = file.mimeType || guessMimeTypeFromFileName(file.fileName)
    
    // 处理文本文件预览
    if (mime.startsWith("text/") || mime === "application/json") {
      setIsLoading(true)
      const loadTextContent = async () => {
        try {
          const response = await fetchFileContent(file.id)

          if (!response.ok) {
            throw new Error("Failed to load text content")
          }

          const text = await response.text()
          setTextContent(text)
          setTextError(false)
        } catch (error) {
          console.error("Failed to load text content:", error)
          setTextError(true)
          setTextContent("")
        } finally {
          setIsLoading(false)
        }
      }

      loadTextContent()
      return
    }
    
    // 处理二进制文件预览（图片、视频、音频、PDF）
    if (
      mime.startsWith("image/") ||
      mime.startsWith("video/") ||
      mime.startsWith("audio/") ||
      mime === "application/pdf"
    ) {
      setIsLoading(true)
      const loadBinaryContent = async () => {
        try {
          const response = await fetchFileContent(file.id)

          if (!response.ok) {
            throw new Error("Failed to load preview")
          }

          const blob = await response.blob()
          const url = URL.createObjectURL(blob)
          setPreviewUrl(url)
          setImageError(false)
        } catch (error) {
          console.error("Failed to load preview:", error)
          setImageError(true)
        } finally {
          setIsLoading(false)
        }
      }

      loadBinaryContent()
    }

    // 清理函数
    return () => {
      if (previewUrl) {
        URL.revokeObjectURL(previewUrl)
      }
    }
  }, [file?.id, open, fetchFileContent])

  if (!file) return null

  const getPreviewContent = () => {
    const mime = file.mimeType || guessMimeTypeFromFileName(file.fileName)

    // Image preview
    if (mime.startsWith("image/")) {
      return (
        <div className="flex items-center justify-center bg-muted rounded-lg p-4 min-h-[400px]">
          {isLoading ? (
            <div className="text-center text-muted-foreground">
              <p>加载中...</p>
            </div>
          ) : !imageError && previewUrl ? (
            <img
              src={previewUrl}
              alt={file.fileName}
              className="max-w-full max-h-[600px] object-contain rounded"
              onError={() => setImageError(true)}
            />
          ) : (
            <div className="text-center text-muted-foreground">
              <FileX className="h-16 w-16 mx-auto mb-4 opacity-20" />
              <p>图片加载失败</p>
            </div>
          )}
        </div>
      )
    }

    // Video preview
    if (mime.startsWith("video/")) {
      return (
        <div className="flex items-center justify-center bg-muted rounded-lg p-4 min-h-[400px]">
          {isLoading ? (
            <div className="text-center text-muted-foreground">
              <p>加载中...</p>
            </div>
          ) : previewUrl ? (
            <video controls className="max-w-full max-h-[600px] rounded">
              <source src={previewUrl} type={mime} />
              您的浏览器不支持视频播放
            </video>
          ) : (
            <div className="text-center text-muted-foreground">
              <FileX className="h-16 w-16 mx-auto mb-4 opacity-20" />
              <p>视频加载失败</p>
            </div>
          )}
        </div>
      )
    }

    // Audio preview
    if (mime.startsWith("audio/")) {
      return (
        <div className="flex flex-col items-center justify-center bg-muted rounded-lg p-12 min-h-[300px]">
          <div className="mb-8 text-center">
            <div className="text-6xl mb-4">🎵</div>
            <p className="text-lg font-medium">{file.fileName}</p>
          </div>
          {isLoading ? (
            <div className="text-center text-muted-foreground">
              <p>加载中...</p>
            </div>
          ) : previewUrl ? (
            <audio controls className="w-full max-w-md">
              <source src={previewUrl} type={mime} />
              您的浏览器不支持音频播放
            </audio>
          ) : (
            <div className="text-center text-muted-foreground">
              <p>音频加载失败</p>
            </div>
          )}
        </div>
      )
    }

    // PDF preview
    if (mime === "application/pdf") {
      return (
        <div className="bg-muted rounded-lg min-h-[600px]">
          {isLoading ? (
            <div className="flex items-center justify-center h-[600px] text-muted-foreground">
              <p>加载中...</p>
            </div>
          ) : previewUrl ? (
            <iframe src={previewUrl} className="w-full h-[600px] rounded-lg" title={file.fileName} />
          ) : (
            <div className="flex items-center justify-center h-[600px] text-muted-foreground">
              <FileX className="h-16 w-16 mb-4 opacity-20" />
              <p>PDF 加载失败</p>
            </div>
          )}
        </div>
      )
    }

    // Text preview
    if (mime.startsWith("text/") || mime === "application/json") {
      return (
        <div className="bg-muted rounded-lg p-6 min-h-[400px] max-h-[600px] overflow-auto">
          {isLoading ? (
            <div className="text-center text-muted-foreground py-12">
              <p>加载中...</p>
            </div>
          ) : textError ? (
            <div className="text-center text-muted-foreground py-12">
              <FileX className="h-16 w-16 mx-auto mb-4 opacity-20" />
              <p>文本文件加载失败</p>
            </div>
          ) : (
            <pre className="text-sm whitespace-pre-wrap font-mono">
              {textContent || "文件内容为空"}
            </pre>
          )}
        </div>
      )
    }

    // Document preview (Office files)
    if (
      mime.includes("document") ||
      mime.includes("spreadsheet") ||
      mime.includes("presentation") ||
      mime.includes("officedocument")
    ) {
      return (
        <div className="flex flex-col items-center justify-center bg-muted rounded-lg p-12 min-h-[400px]">
          <FileX className="h-24 w-24 mb-6 text-muted-foreground opacity-30" />
          <p className="text-lg font-medium mb-2">文档预览</p>
          <p className="text-sm text-muted-foreground text-center mb-6">
            此文档类型暂不支持在线预览
            <br />
            请下载后使用相应软件打开
          </p>
          <Button onClick={() => onDownload(file.id, file.fileName)} className="gap-2">
            <Download className="h-4 w-4" />
            下载文件
          </Button>
        </div>
      )
    }

    // Unsupported file type
    return (
      <div className="flex flex-col items-center justify-center bg-muted rounded-lg p-12 min-h-[400px]">
        <FileX className="h-24 w-24 mb-6 text-muted-foreground opacity-30" />
        <p className="text-lg font-medium mb-2">无法预览</p>
        <p className="text-sm text-muted-foreground text-center mb-6">
          此文件类型不支持预览
          <br />
          请下载后查看
        </p>
        <Button onClick={() => onDownload(file.id, file.fileName)} className="gap-2">
          <Download className="h-4 w-4" />
          下载文件
        </Button>
      </div>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <DialogTitle className="text-xl">{file.fileName}</DialogTitle>
            <Button variant="ghost" size="icon" onClick={() => onDownload(file.id, file.fileName)} className="gap-2">
              <Download className="h-4 w-4" />
            </Button>
          </div>
        </DialogHeader>
        <div className="mt-4">{getPreviewContent()}</div>
      </DialogContent>
    </Dialog>
  )
}
